package rs.mbs2.epics.server.session.dao.bean;

import java.util.List;

import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.Query;

import rs.mbs2.epics.server.entity.User;
import rs.mbs2.epics.server.session.dao.localinterface.UserDaoLocal;

@Stateless
@Local(UserDaoLocal.class)
@TransactionManagement(TransactionManagementType.CONTAINER)
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class UserDaoBean extends GenericDaoBean<User, Integer> implements UserDaoLocal {

	@SuppressWarnings("unchecked")
	@Override
	public User findUserByEmail(String emailAddress) {
		Query q = em.createNamedQuery("findUserByEmail");
		q.setParameter("emailAddress", emailAddress);
		List<User> resultList = q.getResultList();

		if(resultList.isEmpty())
			return null;

		return resultList.get(0);
	}

	@SuppressWarnings("unchecked")
	@Override
	public User findUserByEmailAndPassword(String emailAddress, String password) {
		Query q = em.createNamedQuery("findUserByEmailAndPassword");
		q.setParameter("emailAddress", emailAddress);
		q.setParameter("password", password);
		List<User> resultList = q.getResultList();

		if(resultList.isEmpty())
			return null;

		return resultList.get(0);
	}

	@SuppressWarnings("unchecked")
	@Override
	public User findUserThatCreatedAlbum(Integer albumId) {
		Query q = em.createNamedQuery("findUserThatCreatedAlbum");
		q.setParameter("albumId", albumId);
		List<User> result = (List<User>) q.getResultList();

		return result.size() > 0 ? result.get(0) : null;
	}

}